<template>
  <el-select
    v-model="supplierId"
    filterable
    clearable
    remote
    reserve-keyword
    placeholder="请输入品牌关键字"
    @change="changeSupplierId"
    :remote-method="querySupplierList"
  >
    <el-option
      v-for="item in supplierOptions"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
  </el-select>
</template>

<script>

import {listSupplier} from "@/api/prod/supplier";

export default {
  name: "supplier-selection",
  props: {
    sourceSupplierId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      supplierOptions: [],
      supplierQuery: {
        pageNum: 1,
        pageSize: 50,
        name: "",
      },
      supplierId: null
    }
  },
  created() {
    this.querySupplierList()
  },
  methods: {
    changeSupplierId() {
      this.$emit('update:sourceSupplierId', this.supplierId);
    },
    querySupplierList(keywords) {
      this.supplierQuery.name = keywords;

      if (!keywords) {
        this.supplierQuery.name = ""
      }

      listSupplier(this.supplierQuery).then(response => {
        this.supplierOptions = response.rows.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })
      })
    },
  },
  watch: {
    // sourceSupplierId(val, oldVal) {
    //   console.log("===================")
    //   this.supplierId = val;
    // },
    sourceSupplierId: {
      deep: true,
      immediate: true, //否则在 v-for时渲染 组件时, 这里的 watch 会失效, 造成数据回显绑定失败
      handler: function (val, oldVal) {
        this.supplierId = val;
      }
    }
  }
}
</script>
